/**
 * @Author: liu.yang
 * @Date: 2018-09-17 18:13:11
 * 公共Model
 */

import { getAreas, getInfo, initJpushId } from "../services/public";

const trimAreasData = item => {
  const resData = {
    label: item.areaName,
    value: item.id,
  };
  if (Array.isArray(item.children) && item.children.length > 0) {
    resData.children = item.children.map(citem => trimAreasData(citem));
  }
  return resData;
};

const initData = {
  loading: false,
  userInfo: {},
  areas: [],
  currentMenuName: "",
  goInStatus: "-1", // 记录第一次进入，每次重现进入APP后重制
  version: "1.0.1",
  containerHeight: 0,
};

export default {
  namespace: "public",
  state: {
    ...initData,
  },

  effects: {
    *getAreas(_, { call, put }) {
      const areas = yield call(getAreas);
      let newAreas = [];

      if (Array.isArray(areas) && areas.length > 0) {
        newAreas = areas.map(item => trimAreasData(item));
      }
      yield put({ type: "saveAreas", payload: newAreas });
    },
    *getInfo(_, { call }) {
      const resData = yield call(getInfo);
      return resData;
    },
    *initJPushId({ payload }, { call }) {
      yield call(initJpushId, payload);
    },
  },
  reducers: {
    changeLoadingStatus: (state, { payload }) => ({
      ...state,
      loading: payload,
    }),
    changeMenuData: (state, { payload }) => ({
      ...state,
      menuData: payload,
    }),
    saveUserInfo: (state, { payload }) => {
      // console.log("userinfo", payload);
      return {
        ...state,
        userInfo: payload,
      };
    },
    saveAreas: (state, { payload }) => ({
      ...state,
      areas: payload,
    }),
    saveMenuName: (state, { payload }) => ({
      ...state,
      currentMenuName: payload,
    }),
    changeGoInStatus: (state, { payload }) => ({
      ...state,
      goInStatus: payload,
    }),
    changeContainerHeight: (state, { payload }) => ({
      ...state,
      containerHeight: payload,
    }),
    clear: () => ({
      ...initData,
    }),
  },
  // subscriptions: {
  //   setup({ dispatch }) {
  //     dispatch({ type: 'loadStorage' })
  //   },
  // },
};
